﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusLib
{
    public partial class Shape
    {
        public double Length { get { return Shape_Points.Last().shape_dist_travelled; } }

        // Computes the distances between adjacent points, and stores the 
        // cumulative distance for each point from the start of the shape.
        public void ComputeDistances()
        {
            double cumDistance = 0;
            double prevLat = Shape_Points.First().shape_pt_lat;
            double prevLon = Shape_Points.First().shape_pt_lon;
            foreach (Shape_Point p in Shape_Points)
            {
                double dist = GeoUtils.distance(prevLat, prevLon, p.shape_pt_lat, p.shape_pt_lon, 'M');
                if (double.IsNaN(dist))
                {
                    dist = 0; 
                }
                cumDistance += dist;
                p.shape_dist_travelled = cumDistance;
                prevLat = p.shape_pt_lat; prevLon = p.shape_pt_lon;
            }
            BusLibDataContext.db.SubmitChanges();
        }

        static public Shape Get(int shape_id)
        {
            // Try to find it in the DB:
            BusLibDataContext db = BusLibDataContext.db;
            
            return db.Shapes.SingleOrDefault(s => s.shape_id == shape_id);
        }
    }
}
